'use client';

import { useState } from 'react';
import { Plus } from 'lucide-react';

interface AddTokenFormProps {
  onTokenAdded: () => void;
}

export default function AddTokenForm({ onTokenAdded }: AddTokenFormProps) {
  const [formData, setFormData] = useState({
    symbol: '',
    name: '',
    chain: 'SOLANA',
    contractAddress: '',
    decimals: 18
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setError('');

    try {
      const response = await fetch('/api/tokens', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      });

      if (response.ok) {
        setFormData({
          symbol: '',
          name: '',
          chain: 'SOLANA',
          contractAddress: '',
          decimals: 18
        });
        onTokenAdded();
      } else {
        const errorData = await response.json();
        setError(errorData.error || '添加代币失败');
      }
    } catch (error) {
      setError('网络错误，请重试');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: name === 'decimals' ? parseInt(value) || 18 : value
    }));
  };

  const chainExamples = {
    SOLANA: 'So11111111111111111111111111111111111111112',
    BSC: '0x55d398326f99059fF775485246999027B3197955',
    BASE: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center space-x-3">
        <Plus className="w-6 h-6 text-blue-600" />
        <h2 className="text-2xl font-bold text-gray-900 dark:text-white">
          添加新代币
        </h2>
      </div>

      <div className="card max-w-2xl">
        <form onSubmit={handleSubmit} className="space-y-6">
          {error && (
            <div className="bg-red-50 dark:bg-red-900 border border-red-200 dark:border-red-700 rounded-lg p-4">
              <p className="text-red-800 dark:text-red-200">{error}</p>
            </div>
          )}

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label htmlFor="symbol" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                代币符号 *
              </label>
              <input
                type="text"
                id="symbol"
                name="symbol"
                value={formData.symbol}
                onChange={handleChange}
                className="input"
                placeholder="例如: PEPE"
                required
              />
            </div>

            <div>
              <label htmlFor="name" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                代币名称 *
              </label>
              <input
                type="text"
                id="name"
                name="name"
                value={formData.name}
                onChange={handleChange}
                className="input"
                placeholder="例如: Pepe"
                required
              />
            </div>
          </div>

          <div>
            <label htmlFor="chain" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              区块链 *
            </label>
            <select
              id="chain"
              name="chain"
              value={formData.chain}
              onChange={handleChange}
              className="select"
              required
            >
              <option value="SOLANA">Solana</option>
              <option value="BSC">Binance Smart Chain</option>
              <option value="BASE">Base</option>
            </select>
          </div>

          <div>
            <label htmlFor="contractAddress" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              合约地址 *
            </label>
            <input
              type="text"
              id="contractAddress"
              name="contractAddress"
              value={formData.contractAddress}
              onChange={handleChange}
              className="input"
              placeholder={`例如: ${chainExamples[formData.chain as keyof typeof chainExamples]}`}
              required
            />
            <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
              请输入{formData.chain}链上的代币合约地址
            </p>
          </div>

          <div>
            <label htmlFor="decimals" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              小数位数
            </label>
            <input
              type="number"
              id="decimals"
              name="decimals"
              value={formData.decimals}
              onChange={handleChange}
              className="input"
              min="0"
              max="18"
              placeholder="18"
            />
            <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
              大多数代币使用18位小数
            </p>
          </div>

          <div className="flex justify-end space-x-4">
            <button
              type="button"
              onClick={() => setFormData({
                symbol: '',
                name: '',
                chain: 'SOLANA',
                contractAddress: '',
                decimals: 18
              })}
              className="btn-secondary"
            >
              重置
            </button>
            <button
              type="submit"
              disabled={isSubmitting}
              className="btn-primary flex items-center space-x-2"
            >
              <Plus className="w-4 h-4" />
              <span>{isSubmitting ? '添加中...' : '添加代币'}</span>
            </button>
          </div>
        </form>
      </div>

      {/* 使用说明 */}
      <div className="card bg-blue-50 dark:bg-blue-900 border-blue-200 dark:border-blue-700">
        <h3 className="text-lg font-medium text-blue-900 dark:text-blue-100 mb-3">
          使用说明
        </h3>
        <ul className="space-y-2 text-sm text-blue-800 dark:text-blue-200">
          <li>• 添加代币后，可以在"代币管理"页面配置交易策略</li>
          <li>• 确保合约地址正确，错误的地址可能导致交易失败</li>
          <li>• 建议先小额测试，确认策略正常工作后再增加投入</li>
          <li>• 系统会自动获取代币的价格和RSI数据</li>
        </ul>
      </div>
    </div>
  );
}
